package com.yebxxx.server.controller;


import com.yebxxx.Utils.MinioUtilS;
import com.yebxxx.server.pojo.Admin;
import com.yebxxx.server.pojo.RespBean;
import com.yebxxx.server.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 个人中心
 */
@RestController

public class AdminInfoController {
    @Autowired
    private MinioUtilS minioUtilS;
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Autowired
    private IAdminService adminService;
    @ApiOperation(value = "更新当前用户信息")
    @PutMapping("/admin/info")
    public RespBean updateAdmin(@RequestBody Admin admin, Authentication authentication){
        if(adminService.updateById(admin)){
            SecurityContextHolder.getContext().
                    setAuthentication(new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return  RespBean.success("更新成功！");

        }
        return  RespBean.error("更新失败！");
    }

    @ApiOperation(value = "更新密码")
    @PutMapping("/admin/pass")
    public  RespBean updateAdminPassword(@RequestBody Map<String,Object> info){
        String oldPass = (String) info.get("oldPass");
        String Pass = (String) info.get("Pass");
        Integer adminId = (Integer) info.get("adminId");
        return  adminService.updateAdminPassword(oldPass,Pass,adminId);
    }

    @ApiOperation(value = "更新用户头像")
    @PostMapping("/admin/userface")
    public  RespBean updateAdminUserFace(MultipartFile file,Integer id,Authentication authentication){
        List<String> upload = minioUtilS.upload(new MultipartFile[]{file});
        String url=  endpoint+"/"+bucketName+"/"+upload.get(0);
        return adminService.updateAdminUserFace(url,id,authentication);
    }




    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public RespBean upload(MultipartFile file) {
        List<String> upload = minioUtilS.upload(new MultipartFile[]{file});
        String address=  endpoint+"/"+bucketName+"/"+upload.get(0);
        return RespBean.success("文件上传成功！",address);
    }


}
